﻿<?php

session_start();
require_once '../common/config.php';
require_once '../common/conn.php';
require_once '../common/function.php';
require_once '../db/account.db.php';
require_once '../db/point.db.php';

$action = $_POST['action'];

switch ($action) {
    case 'addCart':
        $res = addCart();
        break;
    case 'deleteCart':
        $res = deleteCart();
        break;
    case 'confirmBuy':
        $res = confirmBuy();
        break;
    case 'qiandao';
        $res = qiandao();
        break;
    default:
        $res['code'] = 2;
        $res['msg'] = '申请类型错误';
}

echo json_encode($res);
/*
 * 每小时签到功能
 */
function qiandao()
{
    $payDB = "payment_db";//这个是我数据库名字
    $paydbc = new DBC($payDB);
    $paymentDB = new pointDB($paydbc);
    $data = $paymentDB->qiandao($_SESSION['AccUnique'],$_SESSION['AccountID']);
    $res['code'] = $data['code'];
    $res['time'] = $data['time'];
    $res['count'] = $data['count'];
    $qdcount = ( ( $data['count'] ) + 1 );
    $sendpoint = $qdcount * 30;
    if ( $qdcount == 5 )
    {
        $sendpoint = ( $qdcount * 30 ) + 50;
    }
    $res['sendpoint'] = $sendpoint;
    $balance_data = $paymentDB->GetPointCount($_SESSION['AccUnique'],$_SESSION['AccountID']);

    $res['balance'] = ( ( $balance_data[0]['balance_point'] )  + $sendpoint );
    if( $res['code'] == 0 )
    {
        $res['msg'] = $data['msg'].'本次签到获得:'.$sendpoint.'积分';
        $paymentDB->AddPoint( $_SESSION['AccUnique'],$_SESSION['AccountID'] , $sendpoint , 3);
    }else if($data['code'] == 1)
    {
        $res['msg'] = $data['msg'].',请再过'.($data['time']).'秒后再来签到.';
    }else{
        $res['msg'] = $data['msg'];
    }
    $paydbc->close();
    return $res;
}
/**
 * 添加到购物车
 */
function addCart() {
    $itemcode = isset($_POST['item_code']) ? addslashes(trim($_POST['item_code'])) : "";
    $array = array();
    if (isset($_SESSION['cart'])) {
        $array = $_SESSION['cart'];
    }
    array_push($array, $itemcode);

    $_SESSION['cart'] = $array;
    $res['code'] = 0;
    return $res;
}

/**
 * 删除购物车中的商品
 * @return int
 */
function deleteCart() {
    $itemcode = isset($_POST['item_code']) ? addslashes(trim($_POST['item_code'])) : "";

    $array = array();
    $newArray = array();
    if (isset($_SESSION['cart'])) {
        $array = $_SESSION['cart'];
        $newArray = $_SESSION['cart'];
    }
    for ($i = 0; $i < count($array); $i++) {
        if ($array[$i] == $itemcode) {
            unset($newArray[$i]);
        }
    }
    $array = array();
    $key = 0;
    foreach ($newArray as $value) {
        $array[$key] = $value;
        $key++;
    }
    $_SESSION['cart'] = $array;
    unset($newArray);

    $res['code'] = 0;
    return $res;
}

/**
 * 购买道具
 */
function confirmBuy() {
    $price = isset($_POST['price']) ? trim($_POST['price']) : "";
    $itemNo = isset($_POST['itemNo']) ? addslashes(trim($_POST['itemNo'])) : "";
    $id_x = isset($_POST['id_x']) ? addslashes(trim($_POST['id_x'])) : "";
    $buy = isset($_POST['buy']) ? addslashes(trim($_POST['buy'])) : "";
    $haoyou = isset($_POST['haoyou']) ? addslashes(trim($_POST['haoyou'])) : "";
    $itemname = isset($_POST['itemname']) ? trim($_POST['itemname']) : "";

//    file_put_contents("post.txt", json_encode($_POST));

    if (!is_numeric($price)) {
        $res['code'] = 3;
        $res['msg'] = "价格不是数字";
        return $res;
    }

    if ($buy == "false" && $haoyou == "") {
        $res['code'] = 4;
        $res['msg'] = "请选择好友";
        return $res;
    }
    $dbc = new DBC();
    $sql = "SELECT * FROM Point_ItemInfo WHERE ItemNo = '" . $itemNo . "'";
    $itemArray = $dbc->fetchData($sql);
    $jiangetime = $itemArray[0]['jiangetime'];//商品的刷新间隔时间戳
    if (isArrayNotEmpty($itemArray)) {
        if ($itemArray[0]['total_amount'] < 1) {
            $res['code'] = 5;
            $res['msg'] = "商品数量不足";
            return $res;
        }
    } else {
        $res['code'] = 6;
        $res['msg'] = "没有对应的商品";
        return $res;
    }

//    $sql = "SELECT * from item_buy_info where ItemIndex = '" . $itemNo . "' AND accunique = '" . $_SESSION['AccUnique'] . "'";
//    $AlearyBuy = $dbc->fetchData($sql);
//    if(count($AlearyBuy) > 1 )
//    {
//        $res['code'] = 7;
//        $res['msg'] = "你当前拥有2个以上未使用的每日礼品,消耗后可购买";
//        return $res;
//    }
    /*
     * 这里来判断每月刷新
     */
    //strtotime();
    $nowtime = time();
    $month_firstday = date('Y-m-01', $nowtime);
    $month_lastday = date('Y-m-d', strtotime("$month_firstday +1 month -1 day"));
    $sql = "SELECT  COUNT(OrderId) AS buyed_number FROM AccountMoneyDetail_Point WHERE itemNo = '" . $itemNo . "' AND AccUnique = '" . $_SESSION['AccUnique'] . "' AND DATEDIFF(day, '" . $month_firstday . "' , UpdateTime) >= 0 AND DATEDIFF(day,UpdateTime, '" . $month_lastday . "') >= 0";
	//file_put_contents("sql2.txt", $sql . "\r\n", 8);
    $buyedArray = $dbc->fetchData($sql);
    if (isArrayNotEmpty($buyedArray)) {
        if ($buyedArray[0]['buyed_number'] >= $itemArray[0]['total_perday']) {
            $res['code'] = 1;
            $res['msg'] = "您已经达到本月购买上限，请下月再次购买";
            return $res;
        }
    }
//这里要获取余额 我之前写了一个方法
    $payDB = "payment_db";//这个是我数据库名字
    $paydbc = new DBC($payDB);
    $paymentDB = new pointDB($paydbc);
    $PointData = $paymentDB->GetPointCount($_SESSION['AccUnique'],$_SESSION['AccountID']);
    $alreadybuydata = $paymentDB->getAlreadyBuyCount($_SESSION['AccUnique'],$itemNo);
    if( isArrayNotEmpty($alreadybuydata))//当前物品已购数量
    {
        $alreadybuynum = count($alreadybuydata);
    }else{
        $alreadybuynum = 0;
    }
    if (isArrayNotEmpty($PointData) && (($PointData[0]['balance_point'] < $price) || ($PointData[0]['balance_point'] < 0))) {
        $res['code'] = 2;
        $res['msg'] = "积分不足";
        return $res;
    } else {
        $result_point = $paymentDB->PointBuyItem($_SESSION['AccUnique'],$_SESSION['AccountID'],$price,$itemNo,1,1,iconv("UTF-8","GB2312",$itemname));
        if( $result_point['code'] == 0 )
        {
            $sqls = array();//定义要执行的sql数组
            $sql = "UPDATE Point_ItemInfo SET total_amount = total_amount - 1 WHERE ItemNo = '" . $itemNo . "'";// 这个是商品每次购买扣掉库存1
            array_push($sqls, $sql);

            //写入订单 AccountMoneyDetail_Point
            $unionNo = date("YmdHis") . "_" . $_SESSION['AccUnique'];
            $num = 1;
            $sql = "INSERT INTO AccountMoneyDetail_Point(AccUnique,ItemIdx,ItemCount,UpdateTime,ItemNo,UnionNo) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $id_x . "','" . $num . "',getDate(),'" . $itemNo . "','" . $unionNo . "')";//这个是订单日志
            array_push($sqls, $sql);
//        file_put_contents("sql.txt", $sql . "\r\n", 8);
            $result = $dbc->executeBatch($sqls);
        }else
        {
            $result = false;
        }
        $dbc->close();
        $paydbc->close();
        if ($result) {
            $balance = $PointData[0]['balance_point'] - $price;
            $alreadybuynum = $alreadybuynum + 1;
            $res['code'] = 0;
            $res['msg'] = "";
            $res['balance'] = $balance;
            $res['left'] = $itemArray[0]['total_amount'] - 1;
            $res['alreadybuynum'] = $alreadybuynum;
            $res['itemname'] = $itemname;
        } else {
            $res['code'] = 1;
            $res['msg'] = "失败";
        }
        return $res;
    }
}